<?php

declare (strict_types = 1);

namespace app\certificate\controller\admin\v1\digitalMachine;

use libs\ALiOss;
use libs\Image;
use think\facade\Db;
use think\Request;

class Machine
{
    public $table = "certificate_digitalmachine";
    /**
     * @Description:
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'] ?? 10;
        $page  = $data['page'] ?? 1;
        $auth  = [];
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($data['name'])) {
            array_push($where, ['name', 'like', "%" . $data['name'] . "%"]);
        }
        if (!empty($data['machineSn'])) {
            array_push($where, ['machineSn', 'like', "%" . $data['machineSn'] . "%"]);
        }
        if (!empty($data['entryOrExit'])) {
            if ($data['entryOrExit'] == 'exit') {
                array_push($where, ['exitDate', '>', "0000-00-00 00:00:00"]);
            } else if ($data['entryOrExit'] == 'entry') {
                array_push($where, ['exitDate', '=', "0000-00-00 00:00:00"]);
            }
        }
        if (!empty($data['digitalMacineTypeUuid'])) {
            $typeLevel = DB::table('certificate_digitalmachinetype')
            ->where(['uuid'=>$data['digitalMacineTypeUuid']])
            ->value('level');
            if($typeLevel == 2){
                array_push($where, ['digitalMacineTypeUuid', '=', $data['digitalMacineTypeUuid']]);
            }else{
                $typeUuid =   DB::table('certificate_digitalmachinetype')
                ->where(['pUuid'=>$data['digitalMacineTypeUuid']])
                ->column('uuid');
                array_push($where, ['digitalMacineTypeUuid', 'in', $typeUuid]);
            }
        }

        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
            array_push($auth, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
            array_push($auth, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        $list = DB::table($this->table)
            ->where($where)
            ->page((int) $page, (int) $limit)
            ->field(['uuid', 'subtitle', 'image', 'prjMachineCode', 'status', 'remark', 'inDate', 'entryDate', 'exitDate', 'corpCode', 'qrCode', 'machineSn', 'digitalMacineTypeUuid','model','swl'])
            ->order(['id desc'])
            ->select()->toArray();
        foreach ($list as $key => &$value) {
            //查询设备的类型 获取 检修流程、许可证、检查表
            $digitalmachinetype = DB::table('certificate_digitalmachinetype')->where($auth)->where("uuid", $value['digitalMacineTypeUuid'])->field(["repairTypeUuid", "machineRiskTypeUuid", "heavyMachineCheckTypeUuid"])->find();

            // //查询设备绑定的企业名称
            // $value['corpName'] = $this->accordUuidGetData('projectinfo_projectcorpinfo', $value['corpCode'], 'corpCode', 'corpName', $request);

            //查询设备绑定的驾驶员数量
            $where1 = [
                ["digitalMachineUuid", "=", $value['uuid']],
                ["isDelete", "=", 0],
            ];
            $value['driverNumbers'] = DB::table('certificate_digitalmachinedriver')->where($where1)->count();

            //查询设备绑定检查表的申请记录数量
            $where1 = [
                ["typeUuid", "=", $digitalmachinetype["heavyMachineCheckTypeUuid"]],
                ["machineUuid", "=", $value["uuid"]],
            ];
            $value["heavymachinecheckNumbers"] = DB::table("certificate_heavymachinecheck")->where($auth)->where($where1)->count();

            //查询设备绑定许可证的申请记录数量
            $where2 = [
                ["typeUuid", "=", $digitalmachinetype["machineRiskTypeUuid"]],
                ["machineUuid", "=", $value["uuid"]],
            ];

            $value["machineriskNumbers"] = DB::table("certificate_machinerisk")->where($auth)->where($where2)->count();

            //查询设备绑定的检修记录申请数量
            //待开发
            $value["repairNumbers"] = 0;
        }
        $count = DB::table($this->table)
            ->where($where)
            ->count('id');

        $data = [
            'list'  => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 添加
     * @param {Request} $request
     */
    public function create(Request $request)
    {
        $data                = $request->data;
        $data['uuid']        = createUuid();
        $data['projectCode'] = $request->authWhere['projectCode'] ?? "";
        $data['corpCode']    = $data['corpCode'];
        $data['isDelete']    = 0;
        $data['status']      = 1;
        $data['entryDate']   = $data['entryData'] ?? date('Y-m-d H:i:s');
        $data['exitDate']    = "0000-00-00 00:00:00";
        $data['model']    = $data['model'];
        $data['swl']    = $data['swl'];
      
        // $check               = DB::table($this->table)->where($request->authWhere)->where([
        //     ['name', '=', $data['name']],
        //     ['isDelete', '=', 0],
        // ])->value('id');
        // if ($check) {
        //     return result(FAIL, '', '设备名称已存在,无法添加!');
        // }
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        $check = DB::table($this->table)->where($where)->where([
            ['machineSn', '=', $data['machineSn']],
            ['status', '=', 1],
        ])->value('id');
        if ($check) {
            return result(FAIL, '', '设备编号已存在,无法添加!');
        }
        $nowPlantNo = DB::table('certificate_digitalmachine')
        ->where([
            'projectCode'=>$request->prjCode
        ])->count();
        $data['prjMachineCode'] = $nowPlantNo++;
        $typeName  = DB::table('certificate_digitalmachinetype')->where([
            'projectCode'=>$request->prjCode,
            'isDelete'=>0,
            'uuid'=>$data['digitalMacineTypeUuid'],
        ])->value('name');
        if(empty($typeName))return result(FAIL,'','設備類型不存在');

        $name = $typeName.'-'.$data['prjMachineCode'].'號機';
        $text = [$typeName,$name];
        $data['qrCode']      = $this->qrCode($data['projectCode'], $data['uuid'], join('\n',$text));

        $data['otherInfo'] = json_encode(isset($data['otherInfo']) ? $data['otherInfo'] : []);

        $data['files'] = json_encode(isset($data['files']) ? $data['files'] : []);

        $checkStatus = $this->checkUuidIsExist($data, $request); //判断相关UUID是否存在
        if ($checkStatus) {
            return result(FAIL, '', $checkStatus);
        }

        DB::startTrans();
        try {
            //添加设备
            $temp = $data['files'];
            unset($data['files']);
            DB::table($this->table)->insert($data);
            $this->editFileList($request, $data['uuid']);
            DB::commit();
            $data['inDate']    = date('Y-m-d', time());
            $data['otherInfo'] = json_decode($data['otherInfo'], true);
            $data['files']     = json_decode($temp, true);
            return result(SUCCESS, $data, '添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
        }
        return result(FAIL, '', '添加失败,请重试');
    }
    /**
     * @Description: 修改
     * @Author: Terry
     * @Date: 2024-01-31 21:02:26
     */
    public function update(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $data['corpCode'] = $data['corpCode'];
        $prjMachineCode = $this->accordUuidGetData($this->table, $uuid, 'uuid', 'prjMachineCode', $request);
        if (empty($prjMachineCode)) {
            return result(FAIL, '', '设备不存在,无法修改!');
        }
        // $check = DB::table($this->table)->where($request->authWhere)->where([
        //     ['uuid', '<>', $uuid],
        //     ['name', '=', $data['name']],
        //     ['isDelete', '=', 0],
        // ])->value('id');
        // if ($check) {
        //     return result(FAIL, '', '设备名称已存在,无法修改!');
        // }
        $where = [
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->authWhere['projectCode']],
        ];

        $check = DB::table($this->table)->where($where)->where([
            ['uuid', '<>', $uuid],
            ['machineSn', '=', $data['machineSn']],
            ['status', '=', 1],
        ])->value('id');
        if ($check) {
            return result(FAIL, '', '擁有人編號 / 序號已存在,无法修改!');
        }
        $check = DB::table($this->table)->where($where)->where([
            ['uuid', '=', $uuid],
        ])->value('id');
        if (!$check) {
            return result(FAIL, '', '设备已被删除,无法修改!');
        }
        $typeName  = DB::table('certificate_digitalmachinetype')->where([
            'projectCode'=>$request->prjCode,
            'isDelete'=>0,
            'uuid'=>$data['digitalMacineTypeUuid'],
        ])->value('name');
        if(empty($typeName))return result(FAIL,'','設備類型不存在');


        $data['otherInfo'] = json_encode(isset($data['otherInfo']) ? $data['otherInfo'] : []);

        $data['files'] = json_encode(isset($data['files']) ? $data['files'] : []);
        $checkStatus   = $this->checkUuidIsExist($data, $request);
        if ($checkStatus) {
            return result(FAIL, '', $checkStatus);
        }
        DB::startTrans();
        try {
            $updateData = [
                'name'                  => $data['name'],
                'subtitle'              => isset($data['subtitle']) ?? '',
                'remark'                => $data['remark'] ?? '',
                'otherInfo'             => $data['otherInfo'],
                // 'digitalMacineTypeUuid' => $data['digitalMacineTypeUuid'],
                'corpCode'              => $data['corpCode'],
                'machineSn'             => $data['machineSn'],
                'entryDate'             => $data['entryDate'],
                'image'                 => $data['image'],
                'model'    =>$data['model'],
                'swl'    =>  $data['swl'],
            ];
            $return = [];
            // if ($data['name'] != $oldName) {
            //     $text = [$typeName,$prjMachineCode.'號機'];
            //     $data['qrCode']      = $this->qrCode($data['projectCode'], $data['uuid'], join('\n',$text));
            //     $return               = ['qrCode' => $updateData['qrCode']];
            // }
            DB::table($this->table)->where($where)->where('uuid', $uuid)->update($updateData);
            $this->editFileList($request, $uuid);
            DB::commit();

            $updateData['otherInfo'] = json_decode($data['otherInfo'], true);

            $updateData['files'] = json_decode($data['files'], true);
            return result(SUCCESS, $updateData, '保存成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();

        }
        return result(FAIL, '', '更新失败');
    }

    public function destroy(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        DB::table($this->table)->where($where)->where('uuid', $data['uuid'])->update([
            'isDelete' => 1,
        ]);
        return result(SUCCESS, '', '删除成功');
    }

    public function checkUuidIsExist($data, $request)
    {
        //用于create和update
        $array = [
            // "projectinfo_projectcorpinfo"         => $data['corpCode'] . "||企业唯一码不存在||corpCode",
            "certificate_digitalmachinetype" => $data['digitalMacineTypeUuid'] . "||设备类型唯一码不存在||uuid",
        ];
        $checkMsg = '';
        foreach ($array as $key => $value) {
            $table    = $key;
            $d        = explode("||", $value);
            $uuid     = $d[0];
            $msg      = $d[1];
            $fileName = $d[2];
            $check    = $this->accordUuidGetData($table, $uuid, $fileName ?? 'uuid', '', $request);
            if (empty($check)) {
                $checkMsg = $msg;
                break;
            }
        }

        return $checkMsg;
    }

    /**
     * @Descripttion:二维码生成
     * @name: qrCode
     * @param {*} $uuid
     */
    private function qrCode($prjCode, $uuid, $text)
    {
        $file = "image/qrcode/{$prjCode}";
        $name = time() . rand(0, 99999) . '.jpg';
        // $path   = "pages/certificate/user/digitalmachine/type/getListy?uuid={$uuid}";
        $path   = "packageC/pages/certificate/machineDigitization/detail/detail?uuid={$uuid}";
        $qrCode = createQrCode($path, $name, $file);
        if (!$qrCode) {
            return false;
        }

        $img  = new image();
        $path = $img->imgButtomAddText($qrCode, $text);

        $exp  = explode('.', $path);
        $oss  = new ALIOss($exp[0], $exp[1]);
        $path = $oss->upload($path);

        return $path;
    }

    /**
     * @Description: 设备进场
     * @param {Request} $request
     */
    public function editMachineEntry(Request $request)
    {
        $data = $request->data;

        $uuids = $data['uuid'];

        if (!is_array($uuids)) {
            return result(FAIL, '', '请选择设备!');
        }

        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }

        $list = DB::table($this->table)
            ->where($where)
            ->where('uuid', "in", $uuids)
            ->where('status', 2)
            ->group('machineSn')
            ->order('id desc')
            ->select()
            ->toArray();
        // ->column('uuid,machineSn');

        if (empty($list)) {
            return result(FAIL, '', '所选设备已是进场状态!');
        }

        $uuids      = array_column($list, 'uuid');
        $machineSns = array_column($list, 'machineSn');

        $list = DB::table($this->table)
            ->where($where)
            ->where('uuid', "in", $uuids)
            ->where('status', 2)
            ->select()
            ->toArray();

        $inLists = DB::table($this->table)
            ->where($where)
            ->where('machineSn', "in", $machineSns)
            ->where('status', 1)
            ->column('machineSn');

        $insertAll = [];
        foreach ($list as $key => &$value) {

            if (in_array($value['machineSn'], $inLists)) {
                continue;
            }

            unset($value['id']);
            $value['uuid']      = createUuid();
            $value['entryDate'] = $data['value'];
            $value['exitDate']  = "0000-00-00 00:00:00";
            $value['status']    = 1;
            $insertAll[]        = $value;
        }
        unset($list);

        if ($insertAll) {
            DB::table($this->table)->insertAll($insertAll);
            return result(SUCCESS, '', '进场成功');
        } else {
            return result(FAIL, '', '所选设备编号已进场');
        }

    }

    /**
     * @Description: 设备离场
     * @param {Request} $request
     */
    public function editMachineExit(Request $request)
    {
        $data = $request->data;

        $uuids = $data['uuid'];

        if (!is_array($uuids)) {
            return result(FAIL, '', '请选择设备!');
        }

        $updateData['exitDate'] = $data['value'];
        $updateData['status']   = 2;
        $where                  = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        DB::table($this->table)->where($where)->where('uuid', "in", $uuids)->where('status', 1)->update($updateData);

        return result(SUCCESS, '', '离场成功');

    }

    /**
     * @Description: 设备绑定驾驶员
     * @param {Request} $request
     */
    public function editDrivers(Request $request)
    {
        $data               = $request->data;
        $digitalMachineUuid = $data['uuid'];

        $globalData = dataMerge($request->uuid, [
            'digitalMachineUuid' => $digitalMachineUuid,
        ]);

        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }

        $check = DB::table($this->table)->where($where)->where('uuid', $digitalMachineUuid)->find();

        if (empty($check)) {
            return result(FAIL, '', '设备不存在');
        }

        if ($check['status'] == 2) {
            return result(FAIL, '', '离场设备不允许绑定驾驶员');
        }

        $newData = array_column($data['value'], 'wxappUserUuid');

        $final = [];
        foreach ($newData as $key => $value) {
            if (empty($value)) {
                continue;
            }
            $final[$key] = $value;
        }

        $files = $final;

        if (empty($final)) {
            DB::table('certificate_digitalmachinedriver')
                ->where([
                    'digitalMachineUuid' => $digitalMachineUuid,
                ])
                ->update(['isDelete' => 1]);

            return result(SUCCESS, '', '更新成功');
        }

        $newData = $final;

        $oldData = DB::table('certificate_digitalmachinedriver')
            ->where(['digitalMachineUuid' => $data['uuid'], 'isDelete' => 0])
            ->column('wxappUserUuid');

        $create = array_diff($newData, $oldData);
        $delete = array_diff($oldData, $newData);

        DB::startTrans();
        try {
            if ($create) {
                foreach ($create as $key => $value) {
                    $insertData[] = array_merge(['wxappUserUuid' => $value, 'uuid' => createUuid()], $globalData);
                }
                DB::table('certificate_digitalmachinedriver')->insertAll($insertData);
            }
            if ($delete) {
                DB::table('certificate_digitalmachinedriver')
                    ->where([
                        'wxappUserUuid'      => $delete,
                        'digitalMachineUuid' => $digitalMachineUuid,
                    ])
                    ->update(['isDelete' => 1]);
            }
            DB::commit();
            return result(SUCCESS, '', '更新成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return result(FAIL, '', '更新失败');
        }

    }

    public function editFileList($request, $digitalMachineUuid = '')
    {

        $data       = $request->data;
        $globalData = [
            'digitalMachineUuid' => $digitalMachineUuid,
        ];
        $files = isset($data['files']) ? $data['files'] : [];

        $final = [];
        foreach ($files as $key => $value) {
            if (empty($value)) {
                continue;
            }
            $final[$key] = $value;
        }

        $files = $final;

        if (empty($final)) {
            DB::table('certificate_digitalmachinefile')
                ->where('isDelete', 0)
                ->where([
                    'digitalMachineUuid' => $digitalMachineUuid,
                ])
                ->update(['isDelete' => 1]);

            return '';
        }

        $oldData = DB::table('certificate_digitalmachinefile')
            ->where(['digitalMachineUuid' => $digitalMachineUuid, 'isDelete' => 0])
            ->column('fileUuid');

        $newData = $files;
        $create  = array_diff($newData, $oldData);
        $delete  = array_diff($oldData, $newData);

        if ($create) {

            foreach ($create as $key => $value) {
                $insertData[] = array_merge(['uuid' => createUuid(), 'fileUuid' => $value], $globalData);
            }
            DB::table('certificate_digitalmachinefile')->insertAll($insertData);
        }
        if ($delete) {
            DB::table('certificate_digitalmachinefile')
                ->where([
                    'fileUuid'           => $delete,
                    'digitalMachineUuid' => $digitalMachineUuid,
                    'corpCode'           => $request->corpCode,
                    'projectCode'        => $request->prjCode,
                ])
                ->update(['isDelete' => 1]);
        }
        return '';

    }
    /**
     * @Description: 获取字典
     * @Author: Terry
     * @Date: 2024-12-04 22:18:48
     * @param {Request} $request
     */
    public function getOptions(Request $request)
    {
        $data  = $request->data;
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        $data['file'] = DB::table('certificate_file')
            ->where($where)
            ->field(['name', 'uuid'])
            ->select();
        return result(SUCCESS, $data);
    }

    /**
     * @Description: 获取数据
     * @param {Request} $request
     */
    public function getDetail(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['uuid'];
        $where = [
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->authWhere['projectCode']]
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        $data = DB::table($this->table)
        ->where($where)
        ->where('uuid', $uuid)
        ->field(['machineSn', 'subtitle', 'image', 'prjMachineCode', 'digitalMacineTypeUuid', 'corpCode', 'name', 'remark', 'uuid', 'qrCode', 'status', 'entryDate', 'exitDate', 'otherInfo', 'inDate','swl','model'])
        ->find();
        if (empty($data)) {
            return result(SUCCESS, [], '');
        }
        $data['driverUuids']            = DB::table('certificate_digitalmachinedriver')->where('digitalMachineUuid', $uuid)->where('isDelete', 0)->column('wxappUserUuid');
        // $data['digitalMachineTypeName'] = $this->accordUuidGetData('certificate_digitalmachinetype', $data['digitalMacineTypeUuid'], 'uuid', 'name', $request);
        // $data['corpName']               = $this->accordUuidGetData('projectinfo_projectcorpinfo', $data['corpCode'], 'corpCode', 'corpName', $request);
        // $data['machineRiskTypeName']       = $this->accordUuidGetData('certificate_machinerisktype', $data['machineRiskTypeUuid'], 'name');
        if (!empty($data['otherInfo'])) {
            $data['otherInfo'] = json_decode($data['otherInfo'], true);
        }
        $data['files'] = DB::table('certificate_digitalmachinefile')
            ->where('digitalMachineUuid', $uuid)
            ->where('isDelete', 0)
            ->column('fileUuid');
        return result(SUCCESS, $data, '');
    }

    protected function accordUuidGetData($table = '', $uuid = '', $fileName = '', $finalName = '', $request)
    {
        //企业表没有isDelete和projectCode ->where('isDelete',0)
        if (empty($finalName)) {
            $finalName = $fileName;
        }
        if ($table == 'projectinfo_projectcorpinfo' || $table == 'certificate_digitalmachinedriver' || $table == 'certificate_digitalmachinefile') {
            $where = [];
        } else {
            $where = [
                ['isDelete', '=', 0],
            ];
            if (!empty($request->authWhere['corpCode'])) {
                array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
            }
            if (!empty($request->authWhere['projectCode'])) {
                array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
            }
        }
        $data = DB::table($table)->where($where)->where("{$fileName}", $uuid)->field(["{$finalName}"])->find();
        return $data["{$finalName}"] ?? '';
    }
    /**
     * @Description: 根据用户UUID获取绑定的设备【实际情况是一个驾驶员可以绑定多个machineSn】
     * @param {Request} $request
     */
    public function accordWorkerUuidGetDigitalMachine(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'] ?? 10;
        $page  = $data['page'] ?? 1;
        $where = [
            ['dmd.isDelete', '=', 0],
            ['dmd.wxappUserUuid', '=', $data['uuid']],
            ['dm.isDelete', '=', 0],
        ];

        $list = DB::table('certificate_digitalmachinedriver')
            ->alias('dmd')
            ->leftJoin("{$this->table} dm", 'dm.uuid = dmd.digitalMachineUuid')
            ->where($where)
            ->page((int) $page, (int) $limit)
            ->field(['dmd.wxappUserUuid', 'dm.inDate', 'dm.corpCode', 'dm.name', 'dm.remark', 'dm.uuid', 'dm.machineSn', 'dm.qrCode', 'dm.subtitle'])
            ->order(['dmd.id desc'])
            ->select()->toArray();
        // foreach ($list as $key => $value) {
        // }

        $count = DB::table('certificate_digitalmachinedriver')
            ->alias('dmd')
            ->leftJoin("{$this->table} dm", 'dm.uuid = dmd.digitalMachineUuid')
            ->where($where)
            ->count('dmd.id');

        $data = [
            'list'  => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }
    /**
     * @Description: 根据设备uuid获取检查表list
     * @param {Request} $request
     */
    public function getDigitalMachineBindHeavyMachineCheckList(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'] ?? 10;
        $page  = $data['page'] ?? 1;
        $where = [
            ['dm.isDelete', '=', 0],
            ['hmc.isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['dm.corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['dm.projectCode', '=', $request->authWhere['projectCode']]);
        }
        if (!empty($data['name'])) {
            array_push($where, ['dm.name', 'like', "%" . $data['name'] . "%"]);
        }
        if (!empty($data['checkStatus'])) {
            if ($data['checkStatus'] == 1) {
                array_push($where, ['hmc.status', '=', 1]);
            } else if ($data['checkStatus'] == 2) {
                array_push($where, ['hmc.status', '=', 2]);
            }
        }

        if (!empty($data['heavyMachineCheckTypeUuid'])) {
            array_push($where, ['hmc.typeUuid', '=', $data['heavyMachineCheckTypeUuid']]);
        }

        if (!empty($data['digitalMachineUuid'])) {
            $uuid      = $data['digitalMachineUuid'];
            $machineSn = $this->accordUuidGetData($this->table, $uuid, 'uuid', 'machineSn', $request);
            if (empty($machineSn)) {
                return result(FAIL, '', '设备不存在!');
            }
            array_push($where, ['dm.machineSn', '=', $machineSn]);
        } else {
            if (!empty($data['machineSn'])) {
                array_push($where, ['dm.machineSn', '=', $data['machineSn']]);
            }
        }

        $list = DB::table($this->table)
            ->alias('dm')
            ->leftJoin('certificate_heavymachinecheck hmc', 'hmc.machineSN = dm.machineSN')
            ->leftJoin("certificate_heavymachinechecktype hmct", 'hmct.uuid = hmc.typeUuid')
            ->where($where)
            ->page((int) $page, (int) $limit)
            ->field(['dm.uuid as digitalMachineUuid', 'dm.name', 'dm.subtitle', 'hmc.machineSn', 'hmc.inDate', 'hmc.uuid as heavyMachineCheckUuid', 'hmc.status', 'hmct.uuid as heavyMachineCheckTypeUuid'])
            ->order(['hmc.id desc'])
            ->select()->toArray();
        foreach ($list as $key => &$value) {
            //查询certificate_heavymachinecheckrecord
            $value['checkRecordList'] = DB::table('certificate_heavymachinecheckrecord')
                ->where('checkUuid', $value['heavyMachineCheckUuid'])
                ->where('isDelete', 0)
                ->field(['checkUuid', 'uuid', 'inDate', 'wxappUserUuid', 'typeUuid', 'areaUuid', 'type'])
                ->order('id desc')
                ->select();
        }

        $count = DB::table($this->table)
            ->alias('dm')
            ->leftJoin('certificate_heavymachinecheck hmc', 'hmc.machineSN = dm.machineSN')
            ->leftJoin("certificate_heavymachinechecktype hmct", 'hmct.uuid = hmc.typeUuid')
            ->where($where)
            ->count('hmc.id');

        $data = [
            'list'  => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 根据设备UUID获取设备的检修列表数据
     * @param {Request} $request
     */
    public function getDigitalMachineBindDigitalMachineRepairList(Request $request)
    {
        $data  = $request->data;
        $limit = $data['limit'] ?? 10;
        $page  = $data['page'] ?? 1;
        $where = [
            ['dm.uuid', '=', $data['digitalMachineUuid']],
            ['dm.isDelete', '=', 0],
            ['dmr.isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['dm.corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['dm.projectCode', '=', $request->authWhere['projectCode']]);
        }
        if (!empty($data['title'])) {
            array_push($where, ['dm.title', 'like', "%" . $data['title'] . "%"]);
        }
        if (!empty($data['checkStatus'])) {
            if ($data['checkStatus'] == 0) {
                array_push($where, ['dmr.status', '=', 0]);
            } else if ($data['checkStatus'] == 1) {
                array_push($where, ['dmr.status', '=', 1]);
            }
        }

        $list = DB::table($this->table)
            ->alias('dm')
            ->leftJoin('certificate_digitalmachinerepair dmr', 'dmr.machineUuid = dm.uuid')
            ->leftJoin('certification_projectWorker pw', 'pw.wxappUserUuid = dmr.wxappUserUuid')
            ->where($where)
            ->page((int) $page, (int) $limit)
            ->field(['dm.uuid as digitalMachineUuid', 'dm.machineSn', 'dmr.title', 'pw.workerName', 'dmr.inDate', 'dmr.auditTime', 'dmr.status', 'dmr.uuid as digitalMachineRepairUuid', 'dmr.description'])
            ->order(['dmr.id desc'])
            ->select()->toArray();
        // foreach ($list as $key => &$value) {
        //     $value['repairRecordList'] = DB::table('certificate_digitalmachinerepairrecord')
        //         ->where('repairUuid', $value['digitalMachineRepairUuid'])
        //         ->where('isDelete', 0)
        //         ->field(['repairUuid', 'uuid', 'inDate', 'wxappUserUuid'])
        //         ->order('id desc')
        //         ->select();
        // }

        $count = DB::table($this->table)
            ->alias('dm')
            ->leftJoin('certificate_digitalmachinerepair dmr', 'dmr.machineUuid = dm.uuid')
            ->leftJoin('certification_projectWorker pw', 'pw.wxappUserUuid = dmr.wxappUserUuid')
            ->where($where)
            ->count('dmr.id');

        $data = [
            'list'  => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }
    /**
     * @Description: 根据检修uuid获取检修record数据
     * @param {Request} $request
     */
    public function getDigitalMachineRepairRecordData(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['digitalMachineRepairUuid'];
        $where = [
            ['dmr.isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['dmr.corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['dmr.projectCode', '=', $request->authWhere['projectCode']]);
        }
        $repair = DB::table("certificate_digitalmachinerepair")
            ->alias('dmr')
            ->leftJoin('certification_projectWorker pw', 'pw.wxappUserUuid = dmr.wxappUserUuid')
            ->where($where)
            ->where('dmr.uuid', $uuid)
            ->field(['dmr.title', 'dmr.description', 'dmr.reason', 'pw.workerName', 'dmr.inDate', 'dmr.auditTime', 'dmr.status', 'dmr.uuid as digitalMachineRepairUuid'])
            ->find();
        $list = DB::table('certificate_digitalmachinerepairrecord')
            ->alias('dmr')
            ->where('repairUuid', $uuid)
            ->where($where)
            ->field(['dmr.uuid', 'dmr.wxappUserUuid', 'dmr.repairUuid', 'dmr.flowOrder', 'dmr.formData', 'dmr.inDate'])
            ->order(['flowOrder asc'])
            ->select()->toArray();

        $data = [
            'repair'           => $repair,
            'repairRecordlist' => $list,
        ];
        return result(SUCCESS, $data, '');
    }
    /**
     * @Description: 根据设备uuid查询附件列表
     * @param {Request} $request
     */
    public function getDigitalMachineFileList(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['digitalMachineUuid'];
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        $list = DB::table('certificate_digitalmachinefile')
            ->where($where)
            ->where('digitalMachineUuid', $uuid)
            ->field(['fileUuid', 'digitalMachineUuid', 'inDate'])
            ->order(['id desc'])
            ->select()->toArray();
        return result(SUCCESS, $list, '');
    }
    /**
     * @Description: 根据文件uuid查询附件详情
     * @param {Request} $request
     */
    public function getFileData(Request $request)
    {
        $data  = $request->data;
        $uuid  = $data['fileUuid'];
        $where = [
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        }
        if (!empty($request->authWhere['projectCode'])) {
            array_push($where, ['projectCode', '=', $request->authWhere['projectCode']]);
        }
        $list = DB::table('certificate_file')
            ->where('uuid', $uuid)
            ->where($where)
            ->field(['uuid', 'name', 'expireTime', 'expireStartTime', 'subtitle', 'inDate', 'file', 'formData', 'fileType'])
            ->order(['id desc'])
            ->select()->toArray();
        foreach ($list as $key => &$value) {
            $value['formData'] = json_decode($value['formData'], true);
        }
        return result(SUCCESS, $list, '');
    }
}
